package edu.stanford.prpl.common.util;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.Enumeration;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import edu.stanford.prpl.common.PRPLProperties;

public class IPAddress {

	private static Log log = LogFactory.getLog(IPAddress.class);

	public static InetAddress getInterfaceIP() {

		InetAddress match = null;
		String iname = PRPLProperties.getProperty("prpl.device.net.interface.name");

		if (iname != null) {
			try {
				Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();

				while (e.hasMoreElements()) {
					NetworkInterface netface = (NetworkInterface) e.nextElement();
					String netfaceName = netface.getName();

					Enumeration<InetAddress> e2 = netface.getInetAddresses();

					while (e2.hasMoreElements()) {
						InetAddress ip = (InetAddress) e2.nextElement();

						if (iname.equals(netfaceName) && ip instanceof Inet4Address) {
							match = ip;
							log.debug("Net interface matched. " + netface.getName() + "\tIP address: "
									+ ip.toString());
						}
						log.debug("Net interface: " + netface.getName());
						log.debug("\t\tIP address: " + ip.toString());
						log.debug("\t\tIP address type: " + ip.getClass().getName());
					}
				}
			} catch (Exception e) {
				log.error(e);
			}
		}

		if (match == null) {
			try {
				match = InetAddress.getLocalHost();
				log.error("No net interface name matched. Get local host address: " + match.getHostAddress());
			} catch (UnknownHostException e) {
				log.error(e);
			}
		}

		return match;
	}

	public static void main(String[] args) throws UnknownHostException {
		// IPAddress ip = new IPAddress();
		getInterfaceIP();
	}
}